const { createServer } = require('http')
const https = require("https");
// const history = require("connect-history-api-fallback");
const { parse } = require('url')
const express = require('express')
const path = require("path");
const fs = require("fs");
const next = require('next')

const server = express();
const port = process.env.PORT || 80;
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

const buildPaths = ['/admin', "/static", '/asset-manifest.json', '/asset-manifest.json', '/logo192.png', '/logo512.png', '/manifest.json', '/robots.txt']

const privateKey = fs.readFileSync("../Nginx_SSL/2_hongbin.xyz.key", "utf8");
const certificate = fs.readFileSync(
    "../Nginx_SSL/1_hongbin.xyz_bundle.crt",
    "utf8"
);
const credentials = { key: privateKey, cert: certificate };

app.prepare().then(() => {
    https.createServer(credentials, (req, res) => {
        // Be sure to pass `true` as the second argument to `url.parse`.
        // This tells it to parse the query portion of the URL.
        const parsedUrl = parse(req.url, true)
        const { pathname, query } = parsedUrl
        console.log(pathname);
        const Admin = buildPaths.some(path => pathname.indexOf(path) === 0);
        if (Admin) {
            let pathName = req.url;
            console.log('hi', pathName);
            // 提供一个 icon就不会发起/favicon.ico的请求了
            if (pathName == "/admin") {
                pathName = "/index.html";
            }

            const extName = path.extname(pathName);
            fs.readFile(`./build${pathName}`, function (err, data) {
                if (err) {
                    console.error(err);
                    // res.status(400).json(err);
                    res.write('not found');
                } else {
                    const ext = getExt(extName);
                    res.writeHead(200, { "Content-Type": ext + "; charset=utf-8" });
                    res.write(data);
                }
                res.end();
            });
        } else if (pathname === '/b') {
            app.render(req, res, '/b', query)
        } else {
            handle(req, res, parsedUrl)
        }
    }).listen(443, (err) => {
        if (err) throw err
        console.log('> Ready on https://hongbin.xyz:443')
    })
    createServer((req, res) => {
        // Be sure to pass `true` as the second argument to `url.parse`.
        // This tells it to parse the query portion of the URL.
        const parsedUrl = parse(req.url, true)
        const { pathname, query } = parsedUrl
        console.log(pathname);
        const Admin = buildPaths.some(path => pathname.indexOf(path) === 0);
        if (Admin) {
            let pathName = req.url;
            console.log('hi', pathName);
            // 提供一个 icon就不会发起/favicon.ico的请求了
            if (pathName == "/admin") {
                pathName = "/index.html";
            }

            const extName = path.extname(pathName);
            fs.readFile(`./build${pathName}`, function (err, data) {
                if (err) {
                    console.error(err);
                    // res.status(400).json(err);
                    res.write('not found');
                } else {
                    const ext = getExt(extName);
                    res.writeHead(200, { "Content-Type": ext + "; charset=utf-8" });
                    res.write(data);
                }
                res.end();
            });
        } else if (pathname === '/xinLove' || pathname.indexOf('renxi') !== -1) {
            let pathName = req.url;
            console.log('hi', pathName);
            // 提供一个 icon就不会发起/favicon.ico的请求了
            if (pathName == "/xinLove") {
                pathName = "/index.html";
            }

            const extName = path.extname(pathName);
            fs.readFile(`./xinLove${pathName}`, function (err, data) {
                if (err) {
                    console.error(err);
                    // res.status(400).json(err);
                    res.write('not found');
                } else {
                    const ext = getExt(extName);
                    res.writeHead(200, { "Content-Type": ext + "; charset=utf-8" });
                    res.write(data);
                }
                res.end();
            });
        } else {
            handle(req, res, parsedUrl)
        }
    }).listen(port, (err) => {
        if (err) throw err
        console.log('> Ready on http://hongbin.xyz:' + port)
    })
})

const EXT = {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/js",
    ".ico": "image/x-icon",
    ".png": "image/png",
};
// 获取后缀名
getExt = extName => {
    return EXT[extName];
};